<template>
  <cj-popup v-model="openAddAddress" round position="bottom" class="h85p" @close="closeAddAddress">
    <div class="c-text-hidden c-bg-sgray c-br-tr20 c-br-tl20 c-flex-column c-h">
      <div class="c-fs28 c-fw600 c-fc-xblack c-hh80 c-flex-row c-flex-center c-bg-white c-w100 c-flex-shrink0 c-bd-b1">
        <span class="iconfont c-fs22 c-fc-sgray c-pa c-p-l24 c-p-t0 c-p-t30" @click="goBack">&#xe6a4;</span>
        {{ modalType == 1 ? '选择地址' : modalType == 2 ? '新增地址' : '编辑地址' }}
      </div>
      <div id="addrList" class="c-ph24 c-pt24 c-contexty-scroll c-flex-grow1 c-w100">
        <template v-if="modalType == 1">
          <div v-for="(item, index) in addressList" :key="index" :class="addrId == item.addrId ? 'theme-bd1' : ''" class="c-ph24 c-pv24 c-bg-white c-br12 c-mb20" @click="selectAddr(item)">
            <div class="c-flex-row c-aligni-center">
              <div class="c-w0 c-flex-grow1">
                <div class="c-flex-row c-aligni-center c-w90">
                  <div v-if="addrId == item.addrId" class="iconfont c-fs24 theme-fc c-mr12">&#xe6eb;</div>
                  <div class="c-fs28 c-fw600 c-fc-xblack c-text-ellipsis1">{{ item.name }}</div>
                  <div class="c-fs28 c-fw600 c-fc-xblack c-ml26 c-ws-n c-lh">{{ item.mobile }}</div>
                  <div v-if="item.status == 1" class="c-fs16 c-ww48 c-hh24 c-flex-row c-flex-center theme-bg c-fc-white c-ml12 c-flex-shrink0 c-ws-n c-br4">默认</div>
                </div>
                <div class="c-fs24 c-fc-xblack c-w90 c-text-ellipsis1 c-mt16">
                  <span>{{ item.province }}</span>
                  <span>{{ item.city }}</span>
                  <span>{{ item.area }}</span>
                  <span>{{ item.address }}</span>
                </div>
              </div>
              <div class="iconfont c-fs26 c-fc-gray" @click.stop="clickEidt(item.addrId)">&#xe90e;</div>
            </div>
          </div>
          <loading-status-tem :data-status="dataStatus" no-data-text="暂无收货地址，点击下方添加"></loading-status-tem>
        </template>
        <template v-else>
          <div class="c-bg-white c-ph24 c-br12 c-mb20">
            <div class="c-flex-row c-aligni-center c-hh88">
              <span class="c-fs24 c-fc-xblack c-ww136">收货人</span>
              <input v-model="addressInfo.name" type="text" class="input-right bd1 c-fs24 c-flex-grow1 c-w0 c-fc-xblack c-bd-b1" placeholder="请输入收货人姓名" />
            </div>

            <div class="c-flex-row c-aligni-center c-hh88">
              <span class="c-fs24 c-fc-xblack c-ww136">联系电话</span>
              <input v-model="addressInfo.mobile" type="tel" class="input-right bd1 c-fs24 c-flex-grow1 c-w0 c-fc-xblack c-bd-b1" placeholder="请输入联系电话" />
            </div>

            <div class="c-flex-row c-aligni-center c-hh88">
              <span class="c-fs24 c-fc-xblack c-ww136">所在地区</span>
              <div class="c-flex-grow1 c-w0 c-h bd1 c-flex-column c-justify-center">
                <div class="c-flex-row c-fc-xblack c-fs24 picker-address">
                  <div v-if="showAddress" v-transfer-dom>
                    <div class="modal"></div>
                  </div>
                  <x-address
                    v-model="addrValue"
                    :theme-color="$getThemeColor()"
                    value-text-align="left"
                    title=""
                    :list="addressData"
                    raw-value
                    placeholder="请选择所在地区"
                    :show.sync="showAddress"
                    class="c-flex-grow1 c-fc-xblack"
                    :popup-style="{ zIndex: 9999, color: '#333333' }"
                  ></x-address>
                </div>
              </div>
            </div>

            <div class="c-flex-row c-pt28 minh56">
              <span class="c-fs24 c-fc-xblack c-ww136">详细地址</span>
              <textarea v-model="addressInfo.address" type="text" class="c-bd0 c-fs24 c-flex-grow1 c-w0 c-fc-xblack" placeholder="请输入街道、楼牌号等"></textarea>
            </div>
          </div>
          <div class="c-bg-white c-ph24 c-br12 c-flex-row c-aligni-center c-justify-sb c-hh88 c-mb40">
            <div class="c-fs24 c-fc-xblack c-flex-row c-aligni-center">设为默认地址</div>
            <x-switch v-model="addressInfo.isDefult" :theme-color="$getThemeColor()" title="" :value-map="[false, true]"></x-switch>
          </div>
        </template>
      </div>
      <div class="c-hh88 c-bg-white c-ph24 c-flex-row c-aligni-center c-w100 c-flex-shrink0 c-bd-t1">
        <div v-if="modalType == 1" class="theme-bg c-fs28 c-fc-white c-hh64 c-flex-row c-flex-center c-br32 c-w0 c-flex-grow1" @click="addAddr">新增地址</div>
        <div v-if="modalType == 2" class="theme-bg c-fs28 c-fc-white c-hh64 c-flex-row c-flex-center c-br32 c-w0 c-flex-grow1" @click="clickSave">保存并使用</div>
        <template v-if="modalType == 3">
          <div class="c-bd1-ccc c-fs28 c-fc-xblack c-hh64 c-flex-row c-flex-center c-br32 c-ww200 c-mr14" @click="clickDel">删除</div>
          <div class="theme-bg c-fs28 c-fc-white c-hh64 c-flex-row c-flex-center c-br32 c-w0 c-flex-grow1" @click="clickSave">保存地址</div>
        </template>
      </div>
    </div>
  </cj-popup>
</template>

<script>
import loadingStatusTem from '@/components/templates/common/loadingStatusTem.vue';
import { XSwitch, XAddress } from 'ckjrweb-mp-ui/src/components/index';
import { loadBMap } from '@/utils/loadBMap.js';
import { utilJs, wxUtilJs } from '@/utils/common.js';
let pageIndex = 1;
let isClickIng = false;
let currentEditId = 0;
export default {
  name: 'AddAddressModal',
  components: {
    XSwitch,
    XAddress,
    loadingStatusTem
  },
  props: {
    openAddAddress: {
      type: Boolean,
      default: false
    },
    editAddressId: {
      type: Number,
      default: 0
    },
    isNeed: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      addrValue: [],
      addressData: [],
      isSubmit: true, // 防止多次提交
      companyAuth: JSON.parse(localStorage.getItem('companyAuth')),
      isOpenGetLocation: true, // 是否开启定位
      isWeiXin: true,
      showAddress: false,
      addressList: [],
      dataStatus: 'HAS_MORE_DATA',
      modalType: 1, // 1: 地址列表 2: 添加地址 3： 编辑地址
      addressInfo: {
        no: 1,
        name: '',
        mobile: '',
        provinceId: '',
        cityId: '',
        areaId: '',
        address: '',
        postcode: '',
        isDefult: true
      },
      addrId: 0
    };
  },
  computed: {
    isNeedFillArea() {
      // 是否需要必填用户地区（旧版和新版区域代理都需要）, 私人订制,enableShareholderAreaAgent股东区域代理必填地区
      return (
        this.enableAreaAgent == 1 ||
        (this.companyAuth && this.companyAuth.enableNewAreaAgent == 1) ||
        this.companyId == 'ww67ok' ||
        (this.companyAuth && this.companyAuth.enableShareholderAreaAgent == 1)
      );
    }
  },
  watch: {
    openAddAddress(val) {
      // this.$emit('update:openAddAddress', val);
      if (this.openAddAddress) {
        this.addrId = this.editAddressId;
        this.modalType = 1;
        if (this.addressList.length == 0) {
          this.initData();
          pageIndex = 1;
          this.dataStatus = 'HAS_MORE_DATA';
          this.getAddressList();
        }
      }
    }
  },
  beforeCreate() {},
  mounted() {
    this.isWeiXin = utilJs.isWeiXin();
    this.getAreaListForAgent();
    if (document.getElementById('addrList')) {
      document.getElementById('addrList').addEventListener('scroll', this.handleScroll);
    }
  },
  methods: {
    initData() {
      this.modalType = 1;
      this.addrValue = [];
      this.addressList = [];
      this.addressInfo = {
        no: 1,
        name: '',
        mobile: '',
        provinceId: '',
        cityId: '',
        areaId: '',
        address: '',
        postcode: '',
        isDefult: true
      };
      pageIndex = 1;
      this.dataStatus = 'HAS_MORE_DATA';
    },
    goBack() {
      if (this.modalType == 1) {
        this.closeAddAddress();
      } else {
        this.modalType = 1;
      }
    },
    selectAddr(addrItem) {
      this.addrId = addrItem.addrId;
      this.$emit('selectAddr', addrItem);
      this.closeAddAddress();
    },
    onConfirmDel(e) {
      // 删除确认
      utilJs.postMethod(global.apiurl + 'address/delete', { addrId: currentEditId }, res => {
        this.$showCjToast({
          text: '删除成功',
          type: 'success',
        });
        if (this.addrId == currentEditId) {
          this.addrId = 0;
        }
        this.initData();
        this.getAddressList();
      });
    },
    clickDel() {
      const that = this;
      that.$cjConfirm({
        title: '删除提示',
        titleCenter: true, // 标题是否居中
        message: '确定要删除该地址吗？',
        messageCenter: true, // 内容是否居中
        showMasker: true, // 是否显示透明背景
        clickCloseModal: true, // 是否点击透明背景关闭弹窗
        showCancelButton: true, // 是否显示取消按钮
        onConfirm() {
          that.onConfirmDel();
        }
      });
    },
    addAddr() {
      this.addrValue = [];
      this.addressInfo = {
        no: 1,
        name: '',
        mobile: '',
        provinceId: '',
        cityId: '',
        areaId: '',
        address: '',
        postcode: '',
        isDefult: true
      };
      this.modalType = 2;
    },
    clickSave() {
      if (isClickIng) {
        return;
      }
      if (!this.checkAddressInfo()) {
        return;
      }
      isClickIng = true;
      const that = this;
      const saveData = {
        addrId: this.modalType == 3 ? currentEditId : '',
        name: this.addressInfo.name,
        mobile: this.addressInfo.mobile,
        provinceId: this.addrValue.length > 0 ? this.addrValue[0] : '',
        cityId: this.addrValue.length > 1 ? this.addrValue[1] : '',
        areaId: this.addrValue.length > 2 ? this.addrValue[2] : '',
        address: this.addressInfo.address,
        postcode: '',
        status: this.addressInfo.isDefult ? 1 : 2
      };
      utilJs.postMethod(global.apiurl + 'address/save', saveData, res => {
        isClickIng = false;
        this.$showCjToast({
          text: '保存地址成功',
          type: 'success',
        });
        if (that.modalType == 2) {
          that.addrId = res;
        }
        that.initData();
        that.getAddressList();
      });
    },
    checkAddressInfo() {
      if (!this.addressInfo.name) {
        this.$showCjToast({
          text: '收货人姓名不能为空',
          type: 'warn',
        });
        return false;
      } else if (!utilJs.isPhoneNumber(this.addressInfo.mobile)) {
        this.$showCjToast({
          text: '请输入正确的手机号',
          type: 'warn',
        });
        return;
      } else if (this.addrValue.length <= 0) {
        this.$showCjToast({
          text: '收货人地址不能为空',
          type: 'warn',
        });
        return false;
      } else if (!this.addressInfo.address) {
        this.$showCjToast({
          text: '收货人详细地址不能为空',
          type: 'warn',
        });
        return false;
      }
      return true;
    },
    clickEidt(addrId) {
      this.modalType = 3;
      currentEditId = addrId;
      utilJs.getMethod(global.apiurl + 'address/edit?addrId=' + addrId, res => {
        this.addressInfo = res;
        this.addrValue = ['' + res.provinceId, '' + res.cityId, '' + res.areaId];
        this.addressInfo.isDefult = res.status == 1;
      });
    },
    handleScroll() {
      const scrollTop = document.getElementById('addrList').scrollTop;
      const clientHeight = document.getElementById('addrList').clientHeight;
      const scrollHeight = document.getElementById('addrList').scrollHeight;

      if (scrollTop + clientHeight >= scrollHeight - 20 && this.dataStatus == 'HAS_MORE_DATA') {
        this.getAddressList();
      }
    },
    closeAddAddress() {
      if (this.addressList.length == 0 || this.addrId == 0) {
        // 删除所有地址后，关闭弹窗 || 删除已经选中的地址
        this.$emit('selectAddr', '');
      }
      this.$emit('closeAddAddress');
    },
    // 获取地址列表
    getAddressList() {
      if (this.dataStatus == 'LOADING') {
        return;
      }
      this.dataStatus = 'LOADING';
      utilJs.getMethod(
        global.apiurl + 'address?page=' + pageIndex,
        res => {
          if (pageIndex == 1) {
            this.addressList = res.address.data;
          } else {
            this.addressList = [...this.addressList, ...res.address.data];
          }
          if (res.address.to * 1 == res.address.total * 1) {
            this.dataStatus = res.address.total * 1 == 0 ? 'NO_DATA' : 'NO_MORE_DATA';
          } else {
            this.dataStatus = 'HAS_MORE_DATA';
            pageIndex++;
          }
        },
        failRes => {
          this.dataStatus = 'DATA_ERROR';
        }
      );
    },
    getAddId(list, id) {
      if (list && list.length == 1) {
        return list[0].value;
      }
      let currentId = '';
      list.forEach(item => {
        if (item.parent == id) {
          currentId = item.value;
        }
      });
      return currentId;
    },
    getAddressId(addComp) {
      let provinceId = '';
      const cityIds = [];
      let cityId = '';
      const areaIds = [];
      let areaId = '';
      this.addressData &&
        this.addressData.forEach(item => {
          item.name = ['北京', '天津', '上海', '重庆'].includes(item.name) ? item.name + '市' : item.name;
          if (item.name == addComp.province && item.level == 1) {
            provinceId = item.value;
          }
          if (item.name == addComp.city && item.level == 2) {
            // 防止市名重复
            cityIds.push(item);
          }
          if (item.name == addComp.district && item.level == 3) {
            // 防止区名重复
            areaIds.push(item);
          }
        });
      cityId = this.getAddId(cityIds, provinceId);
      areaId = this.getAddId(areaIds, cityId);
      // this.addrValue = ['' + provinceId, '' + cityId, '' + areaId]
      // 如果定位获取到的数据不完整，就自动弹出选择框
      if (!(provinceId && cityId && areaId)) {
        this.addrValue = [];
        this.isOpenGetLocation = false;
        this.$showCjToast({
          text: '获取定位失败',
          type: 'text'
        });
        // this.$nextTick(() => {
        //   this.showAddress = true
        // })
        return;
      }
      console.log('zzzzzzz', addComp.province, addComp.city, addComp.district, addComp);
      this.addressInfo = {
        no: 1,
        name: '',
        mobile: '',
        provinceId: provinceId,
        cityId: cityId,
        areaId: areaId,
        address: '',
        postcode: '',
        isDefult: true
      };
      this.modalType = 2;
      this.$nextTick(() => {
        this.addrValue = ['' + provinceId, '' + cityId, '' + areaId];
      });
    },
    getLocation() {
      if (!this.isWeiXin) {
        return;
      }
      const that = this;
      wxUtilJs.getLocation().then(
        res => {
          that.getBdAddress(res.longitude, res.latitude);
          that.isOpenGetLocation = true;
        },
        failRes => {
          that.isOpenGetLocation = false;
          that.$showCjToast({
            text: '获取定位失败',
            type: 'text'
          });
          console.log('获取经纬度失败');
        }
      );
    },
    getBdAddress(longitude, latitude) {
      /* eslint-disable */
      let that = this;
      that.$loading.hide();
      that.$loading.show({
        text: '定位中'
      });
      loadBMap().then(BMap => {
        let point = new BMap.Point(longitude, latitude);
        let gc = new BMap.Geocoder();
        gc.getLocation(point, function(rs) {
          that.$loading.hide();
          const addComp = rs.addressComponents;
          // 可以通过addComp对象获取到省、市、县、区、街道多少号等信息
          that.getAddressId(addComp);
        });
      });
    },
    getAreaListForAgent() {
      utilJs.getMethod(
        `${global.apiurl}common/getAreaListForAgent`,
        res => {
          this.addressData = res.data;
        },
        failRes => {}
      );
    }
  },
  activated() {},
  deactivated() {}
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.vux-cell-box:not(:first-child):before {
  border-top: none !important;
}
.bpm .weui-mask {
  z-index: 10001 !important;
}
.bpm .weui-dialog {
  z-index: 40000 !important;
  max-width: 16rem;
  border-radius: 0.5rem;
}
.maxh380 {
  max-height: 9.5rem;
}
.bpm .vux-cell-placeholder {
  color: #ccc !important;
}
.bpm .vux-cell-value {
  color: #333 !important;
}
.errorTipText {
  font-weight: 400;
  font-size: 0.45rem;
  color: #ff300c;
  line-height: 0.65rem;
  position: absolute;
  right: 0;
  bottom: 0;
}
.c-bd1-F1F1F5 {
  border: 1px solid #f1f1f5;
}
.input-right {
  height: 100%;
  border: 0;
  background: none;
  outline: none;
}
.input-right:focus {
  outline: none;
}
.picker-address div {
  /* height: 100% !important; */
  text-align: left !important;
}
.bd1 {
  border-bottom: 1px solid #f6f6f6 !important;
}
.hh752 {
  height: 18.8rem;
}
.minh56 {
  min-height: 1.4rem;
}
.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 9020;
  width: 100%;
  max-width: 16rem;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.3);
}
.h85p {
  height: 85%;
}
</style>
<style>
.picker-address .vux-popup-picker-placeholder {
  color: #ccc !important;
}
#addrList .vux-cell-value {
  color: #333333;
}
</style>
